package com.vendar.quicknote;

import com.vendar.oauth.OAuthHelper;
import com.vendar.oauth.OAuthSinaWeibo;
import com.vendar.oauth.OAuthAccount;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/*
 * activity used for oauthing.
 * input args: what platform(account vendor)
 * out values: user oauth info.
 */
public class OAuthActivity extends Activity {
	private String mVendor = null;
	private OAuthHelper mOAuth = null;
	private OAuthAccount mUserInfo = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.oauth_activity);
		
		//get vendor
		if( getIntent().getExtras() != null ){
			this.mVendor = getIntent().getExtras().getString("vendor");
		}
		this.mVendor = (this.mVendor == null)?OAuthSinaWeibo.WEIBO_VENDOR:this.mVendor;
		this.mOAuth = new OAuthSinaWeibo();
		
		//goto auth page
		if( this.mOAuth == null ) return ;
		//we have to use this activity as singleinstance,
		//thus,we can retrive the result by "onNewIntent" after send auth request.
		//otherwise,we'll stock into a loop here.
		if( !this.mOAuth.GoAuth(this,"QuickNote://OAuthActivity") ){
			Log.e("QuickNote","auth weibo failed!");
			Toast.makeText(this, getResources().getString(R.string.oauth_failed), 100).show();
		}
	}
	
	@Override
	public void onNewIntent(Intent intent){
		//get auth info
		mUserInfo = mOAuth.GetOAuthedUserInfo(intent);
		if( !mOAuth.GetReady() || mUserInfo == null ){
			Toast.makeText(this, R.string.oauth_failed, 500);
			this.finishActivity(RESULT_CANCELED);
			return ;
		}
		
		//return auth result
		Intent resIntent = new Intent();
		Bundle extras = new Bundle();
		extras.putString("vendor", mVendor);
		extras.putString("user_id",mUserInfo.UserId);
		extras.putString("access_token",mUserInfo.AccessToken);
		extras.putString("access_secret",mUserInfo.AccessSecret);
		resIntent.putExtras(extras);
		
		//restart the StartActivity with auth information!
		resIntent.setClass(OAuthActivity.this, StartActivity.class);
		startActivity(resIntent);
		this.finish();
	}
}
